package com.yutel.phone.binh.data.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONObject;
import org.json.JSONTokener;
import org.xml.sax.SAXException;

import android.util.Log;

import com.yutel.phone.binh.data.net.HttpMapper.DataMap;
import com.yutel.phone.binh.data.vo.VideoStream;
import com.yutel.phone.binh.data.xmlhandler.SAXforVideoStreamHandler;

public class VideoHelper {
	private final static String TAG = "VideoHelper";
	private final static String CHARSET = "utf-8";

	/**
	 * 查询视频ID
	 * 
	 * @return
	 * @throws IOException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 */
	public String queryVideoXml(String url) throws IOException,
			ParserConfigurationException, SAXException {
		try {
			HttpMapper mapper = new HttpMapper(new DataMap() {
				@Override
				public String data(InputStream input) {
					String info = getStreamAsString(input, CHARSET);
					String videoId = getVideoURL(info);
					return videoId;
				}
			});
			return (String) mapper.query(url);
		} catch (Exception e) {
			Log.e(TAG, "queryVideoId()", e);
			return null;
		}
	}

	/**
	 * 查询视频详细信息
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 */
	public VideoStream queryVideoStream(String url) throws IOException,
			ParserConfigurationException, SAXException {
		try {
			HttpMapper mapper = new HttpMapper(new DataMap() {
				@Override
				public VideoStream data(InputStream input) {
					try {
						SAXParserFactory spf = SAXParserFactory.newInstance();
						SAXforVideoStreamHandler videoInfohandle = new SAXforVideoStreamHandler();
						SAXParser saxparser = spf.newSAXParser();
						saxparser.parse(input, videoInfohandle);
						return videoInfohandle.getVideoStream();
					} catch (Exception e) {
						Log.e(TAG, "queryVideoStream():", e);
						return null;
					}
				}
			});
			return (VideoStream) mapper.query(url);
		} catch (Exception e) {
			Log.e(TAG, "queryVideoInfo():", e);
			return null;
		}
	}

	public VideoStream queryTime(final VideoStream vs) throws IOException,
			ParserConfigurationException, SAXException {
		try {
			String timeUrl = "http://data.video.qiyi.com/t.hml";
			HttpMapper mapper = new HttpMapper(new DataMap() {
				@Override
				public VideoStream data(InputStream input) {
					try {
						String info = getStreamAsString(input, CHARSET);
						JSONTokener jsonParser = new JSONTokener(info);
						JSONObject timeObj = (JSONObject) jsonParser
								.nextValue();
						vs.getParam().put("time_t", timeObj.getString("t"));
						return vs;
					} catch (Exception e) {
						Log.e(TAG, "queryVideoStream():", e);
						return null;
					}
				}
			});
			return (VideoStream) mapper.query(timeUrl);
		} catch (Exception e) {
			Log.e(TAG, "queryVideoInfo():", e);
			return null;
		}
	}

	public VideoStream buildUrl(final VideoStream vs, String url)
			throws IOException, ParserConfigurationException, SAXException {
		try {
			HttpMapper mapper = new HttpMapper(new DataMap() {
				@Override
				public VideoStream data(InputStream input) {
					try {
						String info = getStreamAsString(input, CHARSET);
						JSONTokener jsonParser = new JSONTokener(info);
						JSONObject timeObj = (JSONObject) jsonParser
								.nextValue();
						vs.getParam().put("play_l", timeObj.getString("l"));
						return vs;
					} catch (Exception e) {
						Log.e(TAG, "queryVideoStream():", e);
						return null;
					}
				}
			});
			return (VideoStream) mapper.query(url);
		} catch (Exception e) {
			Log.e(TAG, "queryVideoInfo():", e);
			return null;
		}
	}

	private String getStreamAsString(InputStream stream, String charset) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					stream, charset));
			StringWriter writer = new StringWriter();
			char[] chars = new char[1024];
			int count = 0;
			while ((count = reader.read(chars)) > 0) {
				writer.write(chars, 0, count);
			}
			return writer.toString();
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "getStreamAsString():", e);
			return null;
		} catch (IOException e) {
			Log.e(TAG, "getStreamAsString():", e);
			return null;
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private String getVideoURL(String html) {
		Pattern pattern = null;
		pattern = Pattern.compile("[\"]*videoId[\" ]*:[ ]*[\"]([^\"]+)[\"]");
		Matcher matcher = pattern.matcher(html);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			sb.append(matcher.group(1));
		}
		if (sb.length() > 0) {
			sb.insert(0, "http://cache.video.qiyi.com/v/");
		}
		return sb.toString();
	}
}
